package com.hzit.cart.controller;

import com.alipay.api.AlipayApiException;
import com.hzit.cart.api.domain.PayAsyncVo;
import com.hzit.cart.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Controller
public class PayController {
	@Autowired
	private PayService payService;
	//5. 异步通知
	@PostMapping("/payed/order/asyncnotify")
	@ResponseBody
	public String asyncNotify(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {
		//5.1 定义返回的map对象
		Map<String,String> params = new HashMap<String,String>();
		//5.2 从请求作用域中得到请求参数
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		String s = payService.asyncNotify(params, vo);
		System.out.println("s = " + s);
		return s;
	}

}
